import Taro, { Component, Config, } from '@tarojs/taro'
var amapFile = require('../../units/amap-wx.js');// 高德地图
var myAmapFun = new amapFile.AMapWX({ key: 'e78a798459dbc28524564f76b4a4532e' });
import { View, Image, Picker, } from '@tarojs/components'
import './index.less'
import { AtForm, AtInput, AtTextarea, AtMessage, AtButton, } from 'taro-ui'
import namedPng from '../../images/addressIcon.png'
var Citys = require("../../units/citys");
import { HTTP } from './../../../common/index';
import { API } from './../../../common/API';
export default class Index extends Component<any, any>{
    constructor() {
        super(...arguments)
        this.state = {
            files: [],
            province: '',
            city: '',
            district: '',
            dateSel: [[], [], []],
            value: [0, 0, 0],
            values: [0, 0, 0],
            address: '请选择省市区',
            detailAddress: '',
            name: '',
            phone: '',
            userInfo: null
        }
    }
    handleChangeName(e) {
        this.setState({
            name: e
        })
    }
    handleChangePhone(e) {
        this.setState({
            phone: e
        })
    }
    handleChangeDetailAddress(e) {
        this.setState({
            detailAddress: e
        })
    }
    onTimeChange = e => {
        this.setState({
            address: ((this.state.province == this.state.city) ? '' : this.state.province) + ' ' + this.state.city + ' ' + this.state.district
        })
    }
    getLocaltionInfo() {
        var that = this;
        Taro.getLocation({
            type: 'wgs84',
            success(res) {
                myAmapFun.getRegeo({
                    success(res) {
                        const province = res[0].regeocodeData.addressComponent.province;
                        const district = res[0].regeocodeData.addressComponent.district;
                        const city = res[0].regeocodeData.addressComponent.city;
                        that.setState({
                            address: province + ' ' + city + ' ' + district,
                            province: province,
                            district: district,
                            city: city.length == 0 ? province : city
                        })
                        setTimeout(() => {
                            that.setLocationValue()
                        }, 100);
                    }
                })
            }
        })
    }

    async setLocationValue() {
        let provinceNum = await this.getArrayIndex(this.state.cityData, this.state.province)
        let cityNum = await this.getArrayIndex(this.state.cityData[provinceNum].sub, this.state.city)
        let districtNum = await this.getArrayIndex(this.state.cityData[provinceNum].sub[cityNum].sub, this.state.district)
        let citys = await this.getCityAndDistricts(provinceNum, cityNum, 1)
        let districts = await this.getCityAndDistricts(provinceNum, cityNum, 2)
        await this.setCitysAndDistrits(citys, districts)
        this.setState({
            dateSel: [this.state.provinces, citys, districts],
            values: [provinceNum, cityNum, districtNum],
        })
    }
    setCitysAndDistrits(citys, districts) {
        this.setState({
            citys,
            districts,
        })
        return 1
    }
    getCityAndDistricts(provinceNum, cityNum, returnwhat) {
        let citys = [];
        let districts = [];
        let res = []
        for (let i = 0; i < this.state.cityData[provinceNum].sub.length; i++) {
            citys.push(this.state.cityData[provinceNum].sub[i].name as never)
        }
        for (let i = 0; i < this.state.cityData[provinceNum].sub[cityNum].sub.length; i++) {
            districts.push(this.state.cityData[provinceNum].sub[cityNum].sub[i].name as never)
        }
        if (returnwhat == 1) {
            res = citys
        } else {
            res = districts
        }
        return res
    }
    getArrayIndex(arr, obj) {
        var i = arr.length;
        while (i--) {
            if (arr[i].name === obj) {
                return i;
            }
        }
        return -1;
    }
    onColumnChange = e => {
        var val = e.detail.value
        var column = e.detail.column
        var t = this.state.values;
        var cityData = this.state.cityData;
        if (val != t[0] && column === 0) {
            const citys = [];
            const districts = [];
            for (let i = 0; i < cityData[val].sub.length; i++) {
                citys.push(cityData[val].sub[i].name as never)
            }
            for (let i = 0; i < cityData[val].sub[0].sub.length; i++) {
                districts.push(cityData[val].sub[0].sub[i].name as never)
            }
            console.log('this.state.provinces[val].name', this.state.provinces[val].name)
            this.setState({
                province: cityData[val].name,
                city: cityData[val].sub[0].name,
                citys: citys,
                district: cityData[val].sub[0].sub[0].name,
                districts: districts,
                values: [val, 0, 0],
                value: [val, 0, 0],
                dateSel: [this.state.provinces, citys, districts],
            })
            return;
        }
        if (val != t[1] && column === 1) {
            const districts = [];
            for (let i = 0; i < cityData[t[0]].sub[val].sub.length; i++) {
                districts.push(cityData[t[0]].sub[val].sub[i].name as never)
            }
            this.setState({
                city: this.state.citys[val],
                district: cityData[t[0]].sub[val].sub[0].name,
                districts: districts,
                dateSel: [this.state.provinces, this.state.citys, districts],
                values: [t[0], val, 0],
                value: [t[0], val, 0]
            })
            return;
        }
        if (val != t[2] && column === 2) {
            this.setState({
                district: this.state.districts[val],
                values: [t[0], t[1], val]
            })
            return;
        }
    }
    componentWillMount() {
        console.log(this.$router.params)
        let that = this;
        Citys.init(that)
        that.setState({
            userInfo: Taro.getStorageSync('userInfo')
        })
    }
    componentDidMount() {
        let that = this;
        const provinces = [];
        const citys = [];
        const districts = [];
        const cityData = that.state.cityData;
        for (let i = 0; i < cityData.length; i++) {
            provinces.push(cityData[i].name as never);
        }
        for (let i = 0; i < cityData[0].sub.length; i++) {
            citys.push(cityData[0].sub[i].name as never)
        }
        for (let i = 0; i < cityData[0].sub[0].sub.length; i++) {
            districts.push(cityData[0].sub[0].sub[i].name as never)
        }
        that.setState({
            dateSel: [provinces, citys, districts],
            district: districts[0],
            city: citys[0],
            province: provinces[0],
            provinces,
            citys,
            districts
        })
    }
    handleClick(type, message) {
        Taro.atMessage({
            'message': message,
            'type': type,
        })
    }
    // 提交地址信息
    submitAddressInfo() {
        let that = this;
        let name = this.state.name;
        let phone = this.state.phone;
        let detailAddress = that.state.detailAddress;
        let data1 = {
            address: that.state.detailAddress,
            city: that.state.city,
            output: 'json',
            key: "b56445ed2115bca20b054300102d7ac5"
        }
        Taro.request({
            url: 'https://restapi.amap.com/v3/geocode/geo',
            method: 'GET',
            data: data1,
            success: (res) => {
                if (res.data.geocodes.length == 0) {
                    that.handleClick('error', '地址解析失败，请核验后再试！')
                } else {
                    let laong = res.data.geocodes[0].location.split(',');
                    let data = {
                        userId: that.state.userInfo.sell_id,
                        name,
                        province: this.state.province,
                        city: this.state.city,
                        district: this.state.district,
                        longitude: laong[0],
                        latitude: laong[1],
                        phone,
                        detailAddress
                    }
                    HTTP(API.ADDADDRESS, data, 'POST').then((res: any) => {
                        if (res.code == 200) {
                            Taro.showToast({
                                title: res.message,
                                icon: 'success',
                                duration: 1200
                            })
                            setTimeout(() => {
                                Taro.switchTab({
                                    url: '/pages/addressList/index'
                                })
                            }, 1200);
                        } else {
                            Taro.showToast({
                                title: res.message,
                                icon: 'none',
                                duration: 2000
                            })
                        }
                    })
                }
            },
            fail: (e) => {
                console.log('fail', e)
                this.handleClick('error', '请求失败！')
                return
            }
        })
    }
    componentWillUnmount() {
        console.log('componentWillUnmount')
    }
    onJump(data) {
        console.log(11, data)
    }
    componentDidShow() {
        console.log('componentDidShow')
    }

    componentDidHide() {
        console.log('componentDidHide')
    }
    /**
     * 指定config的类型声明为: Taro.Config
     *
     * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
     * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
     * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
     */
    config: Config = {
        navigationBarTitleText: '新增地址'
    }

    render() {
        return (
            <View className='container'>
                <AtMessage />
                <View className='index'>
                    <AtForm>
                        <AtInput
                            name='value1'
                            title='联系人 :'
                            type='text'
                            placeholder='联系人'
                            value={this.state.name}
                            onChange={this.handleChangeName.bind(this)}
                        />
                        <AtInput
                            name='value2'
                            title='手机号 :'
                            type='number'
                            placeholder='手机号'
                            value={this.state.phone}
                            onChange={this.handleChangePhone.bind(this)}
                        />
                        <View className='address'>
                            <View className='addc'>
                                <View className='districk'>取货地区：</View>
                                <View className='provice'>
                                    <Picker className='region_picker' mode='multiSelector' value={this.state.values} onChange={this.onTimeChange} onColumnChange={this.onColumnChange} range={this.state.dateSel}>
                                        <View className='selected-text'>{this.state.address}</View>
                                    </Picker>
                                </View>
                                <View className='addressicon'>
                                    <Image src={namedPng} onClick={this.getLocaltionInfo} />
                                </View>
                            </View>
                        </View>
                        <View className='detail-address'>
                            <View className='districk' style='margin-right:0px;'>门牌号：</View>
                            <View className='deatail-textarea' style={this.state.value == '' ? '' : 'color:#333;'}>
                                <AtTextarea
                                    value={this.state.detailAddress}
                                    onChange={this.handleChangeDetailAddress.bind(this)}
                                    placeholder='门牌号...'
                                    height={100}
                                    count={false}
                                />
                            </View>
                        </View>

                    </AtForm>
                </View>
                <AtButton type='primary' circle={true} onClick={this.submitAddressInfo.bind(this)}>确定</AtButton>
            </View>
        )
    }
}
